<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
function testwrite($d)
{
    $tfile = "_test.txt";
    $fp    = @fopen($d . "/" . $tfile, "w");
    if (!$fp) {
        return false;
    }
    fclose($fp);
    $rs = @unlink($d . "/" . $tfile);
    if ($rs) {
        return true;
    }
    return false;
}

function dir_create($path, $mode = 0777)
{
    if (is_dir($path))
        return true;
    $ftp_enable = 0;
    $path       = sp_dir_path($path);
    $temp       = explode('/', $path);
    $cur_dir    = '';
    $max        = count($temp) - 1;
    for ($i = 0; $i < $max; $i++) {
        $cur_dir .= $temp[$i] . '/';
        if (@is_dir($cur_dir))
            continue;
        @mkdir($cur_dir, 0777, true);
        @chmod($cur_dir, 0777);
    }
    return is_dir($path);
}

function sp_dir_path($path)
{
    $path = str_replace('\\', '/', $path);
    if (substr($path, -1) != '/')
        $path = $path . '/';
    return $path;
}

/**
 * 切分SQL文件成多个可以单独执行的sql语句
 * @param $file sql文件路径
 * @param $tablePre 表前缀
 * @param string $charset 字符集
 * @param string $defaultTablePre 默认表前缀
 * @param string $defaultCharset 默认字符集
 * @return array
 */
function split_sql($file, $tablePre, $charset = 'utf8', $defaultTablePre = 'ty_', $defaultCharset = 'utf8')
{
    if (file_exists($file)) {
        //读取SQL文件
        $sql = file_get_contents($file);
        $sql = str_replace("\r", "\n", $sql);
        $sql = str_replace("BEGIN;\n", '', $sql);//兼容 navicat 导出的 insert 语句
        $sql = str_replace("COMMIT;\n", '', $sql);//兼容 navicat 导出的 insert 语句
        $sql = str_replace($defaultCharset, $charset, $sql);
        $sql = trim($sql);
        //替换表前缀
        $sql  = str_replace(" `{$defaultTablePre}", " `{$tablePre}", $sql);
        $sqls = explode(";\n", $sql);
        return $sqls;
    }

    return [];
}

function execute_sql($db, $sql)
{
    $sql = trim($sql);
    preg_match('/CREATE TABLE .+ `([^ ]*)`/', $sql, $matches);
    if ($matches) {
        $table_name = $matches[1];
        $msg        = "创建数据表{$table_name}";
        try {
            $db->execute($sql);
            return [
                'error'   => 0,
                'message' => $msg . ' 成功！'
            ];
        } catch (\Exception $e) {
            return [
                'error'     => 1,
                'message'   => $msg . ' 失败！',
                'exception' => $e->getTraceAsString()
            ];
        }

    } else {
        try {
            $db->execute($sql);
            return [
                'error'   => 0,
                'message' => 'SQL执行成功!'
            ];
        } catch (\Exception $e) {
            return [
                'error'     => 1,
                'message'   => 'SQL执行失败！',
                'exception' => $e->getTraceAsString()
            ];
        }
    }
}

function create_db_config($config)
{
    if (is_array($config)) {
        $str    = "<?php\n";
        $str   .= "return [\n";
        $str   .= "'hostname' => \"{$config['hostname']}\",\n
                    'database' => \"{$config['database']}\",\n
                    'username' => \"{$config['username']}\",\n
                    'password' => \"{$config['password']}\",\n
                    'hostport' => \"{$config['hostport']}\",\n
                    'charset' => \"{$config['charset']}\",\n
                    'prefix' => \"{$config['prefix']}\",";
        $str   .= "];";
        $url1   = CMS_ROOT.'config/db.php';
        try {
            file_put_contents($url1, $str);
        } catch (\Exception $e) {

            return false;

        }

        return true;
    }
}

function create_site_config($config)
{
    if (is_array($config)) {
        $str    = "<?php\n";
        $str   .= "return [\n";
        $str   .= "'website_name' => \"{$config['website_name']}\",\n
                    'site_domain' => \"{$config['site_domain']}\",\n
                    'seo_title' => \"{$config['seo_title']}\",\n
                    'seo_keywords' => \"{$config['seo_keywords']}\",\n
                    'seo_description' => \"{$config['seo_description']}\",\n
                    'hot_line' => \"\",\n
                    'copyright' => \"©天翼瀚潮网络\",\n
                    'technical_support' => \"技术支持：天翼瀚潮网络\",\n
                    'stats_code' => \"\",\n
                    'url_rewrite' => \"0\",\n
                    'url_html_suffix' => \"html\",\n
                    'soft_type' => \"doc xls xlsx\",\n
                    'soft_size' => \"2\",\n
                    'img_type' => \"jpg png jpeg\",\n
                    'img_size' => \"2\",\n
                    'media_type' => \"\",\n
                    'media_size' => \"\",\n
                    'icp' => \"\",\n
                    'baidu_post_token' => \"\",\n
                    'mobile_status' => \"0\",\n";
        $str   .= "];";
        $url1   = CMS_ROOT.'config/config.php';
        try {
            file_put_contents($url1, $str);
        } catch (\Exception $e) {
            return false;
        }
        return true;
    }
}

/**
 * 获取加密的密码
 * @param $pass   密码明文
 * @return string 加密字符串
 */
function get_hash_pass($pass)
{
    $result = md5(md5($pass) . md5('woshinibaba'));
    return $result;
}

function get_root()
{
    $request = \think\Request::instance();
    $root    = $request->root();
    $root    = str_replace('/index.php', '', $root);
    if (defined('APP_NAMESPACE') && APP_NAMESPACE == 'api') {
        $root = preg_replace('/\/api$/', '', $root);
        $root = rtrim($root, '/');
    }

    return $root;
}
